package dao

import models._
import scala.collection.immutable.HashSet
//implementation
import com.db4o.ObjectContainer
import com.db4o.query.Query
import scala.collection.JavaConversions._

object UserDAO extends CommonDAO[User] {
  
  def login(name:String, password:String)(implicit s:Session): Option[User] = {
    val u = findByName(name)
    u match {
      case Some(user:User)  => if(user.password == password) { Some(user) } else {  None }
      case None       => None
    }
  }
  
  def exists(name:String)(implicit s:Session): Boolean = {
    !findByName(name).isEmpty
  }

  def createAndRef(name:String, fullname:String, password:String, photo:String,
  pref:Option[User.Preferences],details:Option[User.Details])(implicit s:Session): Option[User] = {
    val u = new User(name, fullname, password, photo, pref, details, HashSet.empty[User], HashSet.empty[Post], List.empty[Message], new java.util.Date(), Language.SPANISH, Status.ACTIVE)
    if(findByName(name).isEmpty){
      if(save(u)){
        Some(u)
      } else {
        None
      }
    } else {
      play.Logger.warn("Username "+ name +"already in user")
      None
    }
  }
  
  def findByName(name:String)(implicit s:Session) = {
    val query:Query = s.get.query()
    query.constrain(classOf[User])
    query.descend("name").constrain(name)
    val result:java.util.List[User] = query.execute()
    if(!result.isEmpty()){
      val u = result.get(0)
      s.get.activate(u, 9)
      Some(u)
    } else {
      None 
    }
  }
  
  def findById(id:Int)(implicit s:Session) :Option[User] = {
    try{
      val u:User = s.get.ext().getByID(id)
      if(u != null){
        s.get.activate(u, 4) //XXX: Explicit activation
        Some(u)
      } else {
        None
      }
    } catch {
      case ex:Exception => None
    }
  }
  
  def findByMail(mail:String)(implicit s:Session) = {
    val query:Query = s.get.query()
    query.constrain(classOf[User])
    query.descend("mail").constrain(mail)
    val result:java.util.List[User] = query.execute()
    if(!result.isEmpty()){
      Some( result.get(0) )
    } else {
      None 
    }
  }

}